/*
    实现异步日志缓冲区
        1. 线程将数据传入到缓冲区中
        2. 由另一个线程将该数据依次进行落地
*/

#ifndef __M_BUFFER_H__
#define __M_BUFFER_H__

#include "util.hpp"
#include <vector>
#include <cassert>

namespace Log
{
    #define DEFAULT_BUFFER_SIZE (2*1024*1024)
    #define BUFFER_THRESHOLD_SIZE (5*1024*1024)
    #define BUFFER_INCREMENT_SIZE (10*1024*1024)
    class Buffer
    {
    public:
        Buffer()
            :_buffer(DEFAULT_BUFFER_SIZE)
            ,_read_idx(0)
            ,_write_idx(0)
            {}

        // 向缓冲区写入数据
        void push(const char* data,size_t len)
        {
            if(len >= writeAbleSize())
            {
                std::cout << "len: " << len << std::endl;
                std::cout << "writeAbleSize: " << writeAbleSize() << std::endl;
                std::cout << "buffer_size: " << _buffer.size() << std::endl;
                assert(len <= writeAbleSize());
            }

            // 1. 判断扩容
            ensureEnoughSize(len);

            // 2. 写入数据
            std::copy(data,data + len,&_buffer[_write_idx]);
            moveWriter(len);
        }

        // 返回可读数据的起始地址
        const char* begin()
        {
            return &_buffer[_read_idx];
        }
        
        // 返回可读数据的长度
        size_t readAbleSize()
        {
            return (_write_idx - _read_idx);
        }

        // 返回可写数据的长度
        size_t writeAbleSize()
        {
            return _buffer.size() - _write_idx;
        }

        // 对读指针进行偏移操作
        void moveReader(size_t len)
        {
            assert(len + _read_idx <= _write_idx);

            _read_idx += len;
        }

        // 重置读写位置，初始化缓冲区
        void reset()
        {
            _read_idx = 0;
            _write_idx = 0;
        }

        // 对Buffer实现交换操作
        void swap(Buffer& buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(buffer._write_idx,_write_idx);
            std::swap(buffer._read_idx,_read_idx);
        }

        // 判断缓冲区是否为空
        bool empty()
        {
            return _write_idx == _read_idx;
        }

    private:
        // 对写指针进行向后偏移操作
        void moveWriter(size_t len)
        {
            assert(len + _write_idx <= _buffer.size());
            _write_idx += len;
        }

        // 空间扩容
        void ensureEnoughSize(size_t len)
        {
            if(len * 2 < writeAbleSize())
                return;
            
            size_t new_size = 0;
            // 如果没有超过阈值，就翻倍增长
            // 否则就线性增长
            if(_buffer.size() < BUFFER_THRESHOLD_SIZE)
                new_size = _buffer.size() * 2 + len;
            else
                new_size = _buffer.size() + BUFFER_INCREMENT_SIZE + len;
            
            _buffer.resize(new_size);
        }
    private:
        std::vector<char> _buffer;  // 缓冲区 
        size_t _read_idx;            // 读下标
        size_t _write_idx;           // 写下标
    };
}

#endif